//
//  KoiAccountingData.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 20.03.25.
//

import Foundation
class KoiAccountingData {
    private static var userDefaults = UserDefaults.standard
    private static let user_init_pref = "user_init_pref:"
    
    /**
     初始化记账数据
     */
    static func initDefaultData() {
        let uid = KoiAccountingUserManager.standard.userId()
        // 如果有默认账本，就不初始化了，这个判断似乎没有用
        BookManager.standard.initBook()
        logger.info("账本初始化完成")
        let currentBookId = BookManager.standard.currentBookId()
        CategoryManager.standard.createDefaultCategorys(uid: uid, bookId: currentBookId)
        logger.info("类别初始化完成")
        // 初始化数据结束，设置本地标记
        saveNeedInit(uid: uid)
        // 通知服务端更新初始化状态
        KoiAccountingNetApi.standard.updateNeedInit { result in
            switch result {
            case .success:
                KoiAccountingUserManager.standard.updateNeedInit(isNeedInit: 1)
            case .failure(let failure):
                logger.error("updateNeedInit fail \(failure)")
            }
        }
    }
    
    static func isNeedInit(uid: String) -> Bool {
        return userDefaults.bool(forKey: user_init_pref + uid)
    }
    
    static func saveNeedInit(uid: String, needInit:Bool = false) {
        userDefaults.set(needInit, forKey: user_init_pref + uid)
    }
    
    static func clearDefaultData() {
        let uid = KoiAccountingUserManager.standard.userId()
        let bookId = BookManager.standard.currentBookId()
        CategoryManager.standard.clearDefaultCategory(uid: uid, bookId: bookId)
        BookManager.standard.clearDefaultBook()
        saveNeedInit(uid: uid, needInit: true)
    }
}
